package com.apps.ftapp.act;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.IdRes;
import androidx.fragment.app.FragmentActivity;

import com.apps.ftapp.R;
import com.apps.ftapp.util.Constant;
import com.apps.ftapp.util.L;
import com.duobeiyun.bean.ChatBean;
import com.duobeiyun.callback.PlaybackMessageCallback;
import com.duobeiyun.player.PlaybackPlayer;
import com.duobeiyun.util.EncryptUtils;
import com.duobeiyun.widget.PlaybackPlayerView;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;

public class CusomizedPlayBackActivity extends FragmentActivity implements PlaybackMessageCallback, View.OnClickListener {

    private Context mContext;

    String userRole = "2";

    //竖向导航
    private RelativeLayout portraitNaviLayout;
    //横向导航
    private RelativeLayout landscapeNaviLayout;
    private ImageButton landscapeBackBtn;//横向返回按钮
    //private TextView landscapeCourseTitleText;//横向课程名称
    //ppt显示
    private RelativeLayout pptLayout;

    //竖向播放控制
    private RelativeLayout portraitPlaybackControlLayout;
    private ImageButton portraitControlBtn;//竖向播放控制
    private ImageButton portraitFullScreenBtn;//竖向进入全屏
    private SeekBar portraitSeekbar;//竖向进度
    private TextView portraitCurrentTimeText;//竖向当前时间
    private TextView portraitTotalTimeText;//竖向总时间
    private TextView portraitPlaybackSpeedBtn;//竖向回放速度控制
    //横向播放控制
    private RelativeLayout landscapePlaybackControlLayout;
    private ImageButton landscapeControlBtn;//横向播放控制
    private TextView landscapeCurrentTimeText;//横向当前时间
    private ImageButton landscapeFullScreenBtn;//横向退出全屏
    private TextView landscapePlaybackSpeedBtn;//横向回放速度控制
    private TextView landscapeTotalTimeText;//横向总时间
    private SeekBar landscapeSeekbar;//横向进度

    //聊天区域
    private RelativeLayout chatLayout;
    private ListView chatList;
    private RadioGroup chatGroup;
    private RadioButton allMsgBtn, teacherMsgBtn;
    private ProgressBar load;


    private String pid = Constant.PID;
    private String appkey = Constant.APPKEY;
    private String juid = "aaaaaa";
    private String jnickname = "nnnnnnn";
    private String jroomId = "jzf69fb531f4d64ffa9cb4a2c2f4b596ac";
    private String path = "http://playback2.duobeiyun.com/" + jroomId
            + File.separator;
    private int playMod = 0;// 0在线，1离线
    private int jrole = 2;
    private int timeOut = 30000;
    private boolean isFirstRunning = true;
    private NetWorkReceiver netWorkReceiver;
    private boolean isPlayerStart = false;

    String timestamp = String.valueOf(System.currentTimeMillis());
    String baseUrl = "http://api.duobeiyun.com/api/v3/room/enter?";
    String appKey;
    String nickname;
    String partner;
    String roomId;
    String uid;
    String sign;
    String url;
    String title;


    @BindView(R.id.backplayer)
    PlaybackPlayerView playbackPlayerView;

    private PlaybackPlayer playbackPlayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_cusomized_play_back);
        ButterKnife.bind(this);
        this.mContext = this.getApplicationContext();


        Bundle bundle = this.getIntent().getExtras();
        juid = Constant.uid;

        jroomId = bundle.getString("roomId");
        jnickname = bundle.getString("nickname");

        Intent intent = this.getIntent();
        if (intent != null) {
            String purl = intent.getStringExtra("open_url");
            if (purl != null) {
                this.url = purl;
            } else {
                this.appKey = intent.getStringExtra("appKey") != null ? intent.getStringExtra("appKey") : "";
                this.nickname = intent.getStringExtra("nickname") != null ? intent.getStringExtra("nickname") : "";
                this.partner = intent.getStringExtra("partner") != null ? intent.getStringExtra("partner") : "";
                this.roomId = intent.getStringExtra("roomId") != null ? intent.getStringExtra("roomId") : "";
                this.uid = intent.getStringExtra("uid") != null ? intent.getStringExtra("uid") : "";
                this.title = intent.getStringExtra("title") != null ? intent.getStringExtra("title") : "在线回放";
                this.generateUrl();
            }
        } else {
            this.url = "http://www.duobeiyun.com";
        }


        initView();
        initPlayer();
        OtherCallback();
    }

    public void generateUrl() {
        StringBuffer sb = new StringBuffer();
        sb.append("nickname=").append(this.nickname).append("&").append("partner=").append(this.partner).append("&").append("roomId=").append(this.roomId).append("&").append("timestamp=").append(this.timestamp).append("&").append("uid=").append(this.uid).append("&").append("userRole=").append(this.userRole);
        String pMD5Str = sb.toString() + this.appKey;
        this.sign = EncryptUtils.MD5(pMD5Str);
        this.url = this.baseUrl + sb.append("&").append("sign=").append(this.sign).toString();
        L.i("main", this.url);
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (!isFirstRunning) {
            if (playbackPlayer != null) {
                playbackPlayer.recovery();
            }
        }
        if (isFirstRunning) {
            isFirstRunning = false;
        }
    }

    @Override
    protected void onPause() {
        if (playbackPlayer != null) {
            playbackPlayer.pause();
        }
        super.onPause();
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (playbackPlayer != null) {
            playbackPlayer.release();
        }
    }

    public void initView() {
        //竖向导航
        portraitNaviLayout = findViewById(R.id.portrait_navi_layout);
        Button portraitBackBtn = findViewById(R.id.portrait_back);
        portraitBackBtn.setOnClickListener(this);
        //横向导航
        landscapeNaviLayout = findViewById(R.id.landscape_navi_layout);
        landscapeBackBtn = findViewById(R.id.landscape_back);//横向返回按钮
        landscapeBackBtn.setOnClickListener(this);
        //课程名称
        //landscapeCourseTitleText = (TextView) findViewById(R.id.landscape_course_title);//横向课程名称
        //ppt显示
        pptLayout = findViewById(R.id.pptLayout);

        //竖向播放控制
        portraitPlaybackControlLayout = findViewById(R.id.portrait_playback_control_layout);
        //竖直播放和暂停
        portraitControlBtn = findViewById(R.id.portrait_control);//竖向播放控制
        portraitControlBtn.setOnClickListener(this);
        //竖直全屏
        portraitFullScreenBtn = findViewById(R.id.portrait_fullScreen);//竖向进入全屏
        portraitFullScreenBtn.setOnClickListener(this);
        //竖直拖拽
        portraitSeekbar = findViewById(R.id.portrait_seekBar);//竖向进度
        //竖直当前时间
        portraitCurrentTimeText = findViewById(R.id.portrait_current_time);//竖向当前时间
        portraitCurrentTimeText.setText("00:00");
        //竖直总时间
        portraitTotalTimeText = findViewById(R.id.portrait_total_time);//竖向总时间
        portraitTotalTimeText.setText("00:00");
        portraitPlaybackSpeedBtn = findViewById(R.id.portrait_playback_speed);//竖向回放速度控制
        portraitPlaybackSpeedBtn.setOnClickListener(this);
        //横向播放控制
        landscapePlaybackControlLayout = findViewById(R.id.landscape_playback_control_layout);
        //横向播放和暂停
        landscapeControlBtn = findViewById(R.id.landscape_control);//横向播放控制
        landscapeControlBtn.setOnClickListener(this);
        //横向当前时间
        landscapeCurrentTimeText = findViewById(R.id.landscape_current_time);//横向当前时间
        landscapeCurrentTimeText.setText("00:00");
        //横向退出全屏
        landscapeFullScreenBtn = findViewById(R.id.landscape_exit_fullscreen);//横向退出全屏
        landscapeFullScreenBtn.setOnClickListener(this);
        //横向倍速
        landscapePlaybackSpeedBtn = findViewById(R.id.landscape_playback_speed);//横向回放速度控制
        landscapePlaybackSpeedBtn.setOnClickListener(this);
        //横向总时间
        landscapeTotalTimeText = findViewById(R.id.landscape_total_time);//横向总时间
        landscapeTotalTimeText.setText("00:00");
        //横向拖拽
        landscapeSeekbar = findViewById(R.id.landscape_seekBar);//横向进度

        //播放器
        //playbackPlayer = findViewById(R.id.backplayer);

        //聊天区域
        chatLayout = findViewById(R.id.chat_layout);
        allMsgBtn = findViewById(R.id.allMsg);
        teacherMsgBtn = findViewById(R.id.teacherMsg);
        chatGroup = findViewById(R.id.chatGroup);

        chatList = findViewById(R.id.chatList);

        load = findViewById(R.id.load);
    }

    //初始化播放器
    public void initPlayer() {
        playbackPlayer = new PlaybackPlayer(getApplicationContext(), playbackPlayerView);
        L.i("main", pid + ":::" + appkey + "：：" + pid + "::：" + jnickname + "::" + jroomId + "::" + playMod + "::" + jrole);
        playbackPlayer.authInit(pid, appkey);
        playbackPlayer.initPlayInfo(juid, jnickname, jroomId, playMod,
                jrole, timeOut, this);
        if (getOrientation(this)) {
            playbackPlayer.setSeekBar(portraitSeekbar);
        } else {
            playbackPlayer.setSeekBar(landscapeSeekbar);
        }
    }

    public void OtherCallback() {
        chatGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {

            }
        });
    }


    @Override
    public void loadStart() {//开始加载
        load.setVisibility(View.VISIBLE);
        pauseView();
    }

    @Override
    public void handleContent(ChatBean chatBean) {//返回单条聊天信息

    }

    @Override
    public void handleContent(ArrayList<ChatBean> list) {//放回聊天的集合（在回放中应该只有这个）

    }

    @Override
    public void networkNotConnected() {//网络未连接

    }

    @Override
    public void handleClearChat() {//清理聊天信息

    }

    @Override
    public void statusCode(int i, String s) {

    }

    @Override
    public void kickoff() {//账号多处登录
        load.setVisibility(View.GONE);
    }

    @Override
    public void pptMessage(int i, int i1) {

    }

    @Override
    public void connected() {
        load.setVisibility(View.GONE);
        playView();
    }

    @Override
    public void connectFail(String s) {
        load.setVisibility(View.GONE);
    }

//    @Override
//    public void loadFinish() {//加载完毕
//        load.setVisibility(View.GONE);
//        playView();
//    }

//    @Override
//    public void loadFail(String msg) {//加载失败
//        load.setVisibility(View.GONE);
//    }

//    @Override
//    public void connectTimeout() {
//        load.setVisibility(View.GONE);
//    }

//    @Override
//    public void statusCode(int code) {
//        L.i("main", "====" + code);
//    }

//    @Override
//    public void exit() {
//
//    }

    @Override
    public void getTotalTime(String totalTime) {
        portraitTotalTimeText.setText(totalTime);
        landscapeTotalTimeText.setText(totalTime);
    }

//    @Override
//    public void getPPTinfo(int currentpage, int totalpage) {
//
//    }

    @Override
    public void currentTime(String playTime) {
        landscapeCurrentTimeText.setText(playTime);
        portraitCurrentTimeText.setText(playTime);
    }

    @Override
    public void playPuase(boolean b) {
        pauseView();
    }

    @Override
    public void playFinish() {

    }

//    @Override
//    public void playPuase() {
//
//    }

    public void pauseView() {
        landscapeControlBtn.setBackgroundResource(R.drawable.play);
        portraitControlBtn.setBackgroundResource(R.drawable.play);
    }

    public void playView() {
        landscapeControlBtn.setBackgroundResource(R.drawable.stop);
        portraitControlBtn.setBackgroundResource(R.drawable.stop);
    }

    private float speed = 1.0f;

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.portrait_back || v.getId() == R.id.landscape_back) {
            if (!this.isFinishing()) {
                this.finish();
            }
        } else if (v.getId() == R.id.portrait_fullScreen || v.getId() == R.id.landscape_exit_fullscreen) {
            changeScreen();
        } else if (v.getId() == R.id.portrait_playback_speed || v.getId() == R.id.landscape_playback_speed) {
            if (speed == 1.0f) {

                speed = 1.5f;
            } else {
                speed = 1.0f;
            }
            playbackPlayer.setSpeedPlay(speed);
            landscapePlaybackSpeedBtn.setText(speed + "倍速");
            portraitPlaybackSpeedBtn.setText(speed + "倍速");
        } else if (v.getId() == R.id.landscape_control || v.getId() == R.id.portrait_control) {
            if (!isPlayerStart) {
                playbackPlayer.startPlayback();
            } else {
                if (playbackPlayer.playing) {
                    playbackPlayer.recovery();
                } else {
                    playbackPlayer.startPlayback();
                }
                playbackPlayer.playing = !playbackPlayer.playing;
            }

        }
    }

    /**
     * 返回屏幕的方向
     *
     * @param context
     * @return true 为 portrait  false 为 landscape
     */

    public static boolean getOrientation(Context context) {
        return context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (playbackPlayer != null) {

            playbackPlayer.pause();
            if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
                //横向显示
                landscapeNaviLayout.setVisibility(View.VISIBLE);
                landscapePlaybackControlLayout.setVisibility(View.VISIBLE);
                //landscapeCourseTitleText.setVisibility(View.VISIBLE);
                //竖向隐藏
                portraitNaviLayout.setVisibility(View.GONE);
                portraitFullScreenBtn.setBackgroundResource(R.drawable.back);
                portraitPlaybackControlLayout.setVisibility(View.GONE);
                portraitPlaybackSpeedBtn.setVisibility(View.GONE);
                //聊天内容隐藏
                chatLayout.setVisibility(View.GONE);
            } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
                //横向隐藏
                landscapeNaviLayout.setVisibility(View.GONE);
                landscapePlaybackControlLayout.setVisibility(View.GONE);
                //landscapeCourseTitleText.setVisibility(View.GONE);
                //竖向显示
                portraitNaviLayout.setVisibility(View.VISIBLE);
                portraitFullScreenBtn.setBackgroundResource(R.drawable.fullscreen);
                portraitPlaybackSpeedBtn.setVisibility(View.VISIBLE);
                portraitPlaybackControlLayout.setVisibility(View.VISIBLE);
                //聊天内容显示
                chatLayout.setVisibility(View.VISIBLE);
            }
        }
    }

    // 全屏显示（横屏显示）
    public void changeScreen() {
        if (getOrientation(this)) {
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        } else {
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }

    public static void startCusomizedPlayBackActivity(Context context) {
        Intent intent = new Intent(context, CusomizedPlayBackActivity.class);
        context.startActivity(intent);

    }

    class NetWorkReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (manager != null) {
                NetworkInfo[] infos = manager.getAllNetworkInfo();
                if (infos != null) {
                    for (int i = 0; i < infos.length; i++) {
                        NetworkInfo.State state = infos[i].getState();
                        if (NetworkInfo.State.CONNECTED == state) {
                            return;
                        }
                    }
                }
            }
            if (playbackPlayer != null) {
                playbackPlayer.clear();
            }
        }
    }

}
